package ru.mcfr.oxygen.framework.operations.table;

import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.access.AuthorTableAccess;
import ro.sync.ecss.extensions.api.node.AttrValue;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorElement;
import ro.sync.ecss.extensions.api.node.AuthorNode;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ws
 * Date: 09.03.11
 * Time: 14:26
 * To change this template use File | Settings | File Templates.
 */
public class DeleteInsertRowOperation implements AuthorOperation {
    public void doOperation(AuthorAccess authorAccess, ArgumentsMap argumentsMap) throws IllegalArgumentException, AuthorOperationException {
        AuthorDocumentController controller = authorAccess.getDocumentController();
        AuthorSchemaManager manager = authorAccess.getDocumentController().getAuthorSchemaManager();
        AuthorTableAccess tableContainer = authorAccess.getTableAccess();

        String selectedText = "";
        try {
            selectedText = authorAccess.getEditorAccess().getSelectedText();
        } catch (Exception e) {
        }

        try{
            int currentPosition = authorAccess.getEditorAccess().getCaretOffset();
            if (!selectedText.isEmpty())
                currentPosition = authorAccess.getEditorAccess().getSelectionStart();

            AuthorNode cell = controller.getNodeAtOffset(currentPosition);
            while (!cell.getName().equalsIgnoreCase("ячейка"))
                cell = cell.getParent();

            AuthorNode table = cell;
            while (!table.getName().equalsIgnoreCase("таблица"))
                table = table.getParent();

            int[] cellCoord = authorAccess.getTableAccess().getTableCellIndex((AuthorElement) cell);
            int selectedRowNumber = cellCoord[0];
            AuthorElement row = authorAccess.getTableAccess().getTableRow(selectedRowNumber, (AuthorElement) table);
            int columnsCount = authorAccess.getTableAccess().getTableNumberOfColumns((AuthorElement) table);

            if (argumentsMap.getArgumentValue("вид операции").equals("удалить")){
                for (int i = 0; i < columnsCount; i++) {
                    AuthorElement iCell = authorAccess.getTableAccess().getTableCellAt(selectedRowNumber, i, (AuthorElement) table);
                    try {
                        int rowspanValue = Integer.valueOf(iCell.getAttribute("rowspan").getValue());
                        controller.setAttribute("rowspan", new AttrValue("" + (--rowspanValue)), iCell);
                    } catch (Exception e) {
                    }
                }
                controller.deleteNode(row);
                authorAccess.getEditorAccess().setCaretPosition(currentPosition);
                return;
            }

            int pointToInsert = row.getEndOffset() + 1;


            String xmlText = "<строка>";
            //border and colspan copy
            List<AuthorNode> cells = row.getContentNodes();
            for (AuthorNode cel : cells){
                String cellText = "<ячейка";
                AuthorElement aeCell = (AuthorElement) cel;
                int attrsCount = aeCell.getAttributesCount();
                for (int i = 0; i < attrsCount; i++){
                    if (aeCell.getAttributeAtIndex(i).equalsIgnoreCase("colspan") | aeCell.getAttributeAtIndex(i).contains("border")){
                        String attrName = aeCell.getAttributeAtIndex(i);
                        String attrValue = aeCell.getAttribute(attrName).getValue();
                        cellText += " " + attrName + "=\"" + attrValue + "\"";
                    }
                }
                cellText += "/>";

                xmlText += cellText;
            }

            xmlText += "</строка>";

            //rowspan in table
            for (int i = 0; i < columnsCount; i++){
                AuthorElement iCell = authorAccess.getTableAccess().getTableCellAt(selectedRowNumber, i, (AuthorElement) table);
                try {
                    int rowspanValue = Integer.valueOf(iCell.getAttribute("rowspan").getValue());
                    controller.setAttribute("rowspan", new AttrValue("" + (++rowspanValue)), iCell);
                } catch (Exception e){ }
            }

            AuthorDocumentFragment fragment = controller.createNewDocumentFragmentInContext(xmlText, pointToInsert);
            controller.insertFragment(pointToInsert,fragment);
            authorAccess.getEditorAccess().setCaretPosition(currentPosition);

            //controller.insertXMLFragment(xmlText ,pointToInsert);

        } catch (Exception e) {}
    }

    public ArgumentDescriptor[] getArguments() {
        return new ArgumentDescriptor[]{
                new ArgumentDescriptor("вид операции",ArgumentDescriptor.TYPE_STRING,"удалить/вставить"),
                new ArgumentDescriptor("направление",ArgumentDescriptor.TYPE_STRING,"перед/после"),
        };
    }

    public String getDescription() {
        return "Вставить строку после";
    }
}
